package com.zxh.baidu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zxh.util.Constant;
import com.zxh.util.HttpPoolUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.message.BasicHeader;
import org.apache.log4j.Logger;

import java.io.File;

/**
 * Created by zhangxh on 2016/7/11.
 */
public class STTUtil {
    private static Logger logger=Logger.getLogger(STTUtil.class);
    private static final String API_URI = "http://vop.baidu.com/server_api";
    public static String read(byte[] soundByte,String fileFormat) throws Exception {
        logger.debug("请求语识别");
        ByteArrayEntity byteArrayEntity=new ByteArrayEntity(soundByte);
        String httpRes= HttpPoolUtil.postRetStr(API_URI + "?cuid=" + Constant.getPropertity("cuid") + "&token=" + BaiduUtil.getToken(),
                new BasicHeader("Content-Type", "audio/"+fileFormat+"; rate=11000"),byteArrayEntity);
        logger.debug("请求语识别返回："+httpRes);
        JSONObject json= JSON.parseObject(httpRes);
        int err_no=json.getIntValue("err_no");
        if(err_no==0){
            JSONArray results=json.getJSONArray("result");
            return StringUtils.removeEnd(results.get(0).toString(),"，");
        }else{
            logger.debug("请求错误信息:"+json.getString("err_msg"));
            return null;
        }

    }
    public static String read(File soundFile,String fileFormat) throws Exception {
        return read(FileUtils.readFileToByteArray(soundFile),fileFormat);
    }
}
